package cn.bone.auth.security.service.impl;

import cn.bone.auth.security.bean.SysPermission;
import cn.bone.auth.security.bean.SysUser;
import cn.bone.auth.security.mapper.SysPermissionMapper;
import cn.bone.auth.security.mapper.SysUserMapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysPermissionMapper sysPermissionMapper;



//    public static ThreadLocal<SysUser> userThreadLocal = new ThreadLocal<>();


    /*
        因为SysUser继承了UserDetails，所以这里可以直接返回SysUser
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserMapper.selectByUserName(username);

        //用户不存在,抛出自定义的异常
        if(sysUser==null){
            return null;
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<SysPermission> permissions = sysPermissionMapper.listByUsername(username);
        for(SysPermission permission : permissions){
            sysUser.getPermissionTagList().add(permission.getPermissionTag());
        }

        return sysUser;
    }
}
